package com.hqyj.javaSpringBoot.config.shiro;

import com.hqyj.javaSpringBoot.modules.account.entity.Resource;
import com.hqyj.javaSpringBoot.modules.account.entity.Role;
import com.hqyj.javaSpringBoot.modules.account.entity.User;
import com.hqyj.javaSpringBoot.modules.account.service.ResourceService;
import com.hqyj.javaSpringBoot.modules.account.service.RoleService;
import com.hqyj.javaSpringBoot.modules.account.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description：MyRealm
 * @Author ：Cwd
 * @Date ：2021/8/31 19:59
 */
@Component  //注册为 IOC 的一个 bean
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;

    @Override   //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        User user = (User)principals.getPrimaryPrincipal();
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        roles.stream().forEach(item -> {
            simpleAuthorizationInfo.addRole(item.getRoleName());
            List<Resource> resources = resourceService.getResourcesByRoleId(item.getId());
            resources.stream().forEach(ite -> {
                simpleAuthorizationInfo.addStringPermission(ite.getPermission());
            });
        });

        return simpleAuthorizationInfo;
    }

    @Override   // 身份认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        User user = userService.getUserByUserName(userName);
        if (user == null){
            throw new UnknownAccountException("The account don't exist. ");
        }

        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
